package com.lcy.struct.bTreePlus.disk.recovery.undo;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.lcy.struct.bTreePlus.disk.core.BPlusTreeFactory;
import com.lcy.struct.bTreePlus.disk.index.BTreeIndex;
import com.lcy.struct.bTreePlus.disk.item.TreeNode;
import com.lcy.struct.bTreePlus.disk.recovery.RecoveryCenter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author lucongyang
 * @date Created in  10:20
 * @description 删除的逆向操作
 */
class UndoDel {

    static UndoDel getInstance() {
        return Singleton.INSTANCE;
    }

    void doUndo(List<String> undoStrList) {
        List<TreeNode> treeNodeList = new ArrayList<>();
        for (String undoStr:undoStrList) {
            undoStr = undoStr.substring(12);
            TreeNode treeNode = JSONObject.parseObject(undoStr, TreeNode.class);
            treeNodeList.add(treeNode);
        }
        BPlusTreeFactory.batchAdd(treeNodeList, false);
    }

    /**
     * 生成undo日志
     *
     * @param index 主键
     */
    String getUndo(Comparable... index) {
        Object data = BPlusTreeFactory.findDataOnDisk(index);
        if (data == null) {
            return null;
        }
        TreeNode treeNode = new TreeNode();
        BTreeIndex bTreeIndex = new BTreeIndex();
        List<Comparable> list = new ArrayList<>(Arrays.asList(index));
        bTreeIndex.setIndexList(list);
        treeNode.setIndex(bTreeIndex);
        treeNode.setData(data);
        try {
            return "insert into " + RecoveryCenter.getInstance().objectMapper.writeValueAsString(treeNode);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("序列化失败");
        }
    }

    DoUndo.Suitable isSuit() {
        return (undoStr) -> undoStr.startsWith("insert into ");
    }

    private static class Singleton {
        private static final UndoDel INSTANCE = new UndoDel();
    }

    private UndoDel() {
    }
}
